
// 线程局部存储（Thread Local Storage，TLS）是一种特殊的存储方式，它为每个线程分配一块独立的存储空间，使得线程之间的数据隔离。
// Below is the code of /Users/songhz/Desktop/code/Cpp/day1-thread_local.cpp 
#include <iostream>
#include <thread>
#include <chrono>

int main() {
    thread_local int a = 10;

    bool b = true;

    std::cout << "Main thread: b = " << b << std::endl;
    //取反
    b = !b;
    std::cout << "Main thread: b = " << b << std::endl;
    
    // 创建三个线程，每个线程都修改和打印同一个线程局部变量 a
    // 子线程改变a的值并不会影响主线程的 a 值
    std::thread t1([&]() {
        a = 20;
        // 延迟了0.1秒（100毫秒） std::cout << "Thread 1: " << a << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
        std::cout << "Thread 1: " << a << std::endl;
    });

    std::thread t2([&]() {
        a = 30;
        std::cout << "Thread 2: " << a << std::endl;
    });

    std::thread t3([&](){
        a= 100;
        std::cout << "Thread 3: " << a << std::endl;

    });

    // 等待线程结束
    t1.join();
    // 等待线程结束
    t2.join();
    // 这里应该写等待t3结束，但是由于t3没有join，导致主线程结束后异常
    
    //bugfix: join t3
    //libc++abi: terminating
    ///bin/sh: line 1: 48272 Abort trap: 6

    std::cout << "Main thread: " << a << std::endl;

    return 0;
}
